﻿using CodeNotes.Model;
using CodeNotes.BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using MvcCodeNotes.Models;

namespace MvcCodeNotes.Controllers
{
    public class AdminController : Controller
    {
        public static int N_PAGE_SIZE = 10;

        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        public ActionResult Index()
        {
            CW_Menu menu = new CW_Menu
            {
                MenuId = 1,
                MenuName = "Index菜单管理",
                Url = "Menu"
            };
            CW_Menu menu2 = new CW_Menu
            {
                MenuId = 2,
                MenuName = "Index文章管理",
                Url = "Article"
            };
            CW_Menu menu3 = new CW_Menu
            {
                MenuId = 3,
                MenuName = "Index退出登录",
                Url = "Login"
            };

            List<CW_Menu> list = new List<CW_Menu>();
            list.Add(menu);
            list.Add(menu2);
            list.Add(menu3);

            ViewBag.MenuList = list;
            return View(list);
        }


        public ActionResult AdminMenu()
        {
            CW_Menu menu = new CW_Menu
            {
                MenuId = 1,
                MenuName = "菜单管理",
                Url = "Menu"
            };
            CW_Menu menu2 = new CW_Menu
            {
                MenuId = 2,
                MenuName = "文章管理",
                Url = "Article"
            };
            CW_Menu menu3 = new CW_Menu
            {
                MenuId = 3,
                MenuName = "退出登录",
                Url = "Login"
            };

            List<CW_Menu> list = new List<CW_Menu>();
            list.Add(menu);
            list.Add(menu2);
            list.Add(menu3);

            ViewBag.MenuList = list;


            return PartialView("_AdminMenu", list);
        }

        #region 文章管理
        public ActionResult ArticleList(int? page, string keyword)
        {
            int pageSize = 10;
            int pageIndex = page == null ? 0 : Convert.ToInt32(page);
            string sqlStr = "1=1";
            if (!String.IsNullOrEmpty(keyword))
            {
                sqlStr = string.Format("(Title like '%{0}%' or Abstract like '%{0}%')", keyword);
            }
            sqlStr += " order by ArticleId desc";

            List<CW_Article> listTemp = new CW_ArticleLogic().GetModelList(sqlStr);

            //List<CodeNotes.Model.CW_Menu> menuList = new CW_MenuLogic().GetModelList("");
            //List<CW_ArticleView> list = new List<CW_ArticleView>();
            //foreach (CW_Article a in listTemp)
            //{
            //    CW_ArticleView av = new CW_ArticleView();
            //    av.Article = a;
            //    if (a.MenuId > 0)
            //    {
            //        CW_Menu menu = menuList.Where(p => p.MenuId == a.MenuId).FirstOrDefault();
            //        if (menu != null)
            //            av.MenuName = menu.MenuName;
            //    }
            //    list.Add(av);
            //}

            Pagination<CW_Article> paginateNew = new Pagination<CW_Article>(listTemp, pageIndex, pageSize);


            return View(paginateNew);
        }


        public ActionResult ArticleDetails(int id)
        {
            return View();
        }

        public ActionResult ArticleCreate()
        {
            List<CW_Tag> tagList = new CW_TagLogic().GetModelList("");
            ViewBag.tagList = tagList;
            return View();
        }


        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ArticleCreate(CW_Article model, FormCollection collection)
        {

            string logoSrc = "";
            HttpPostedFileBase thumbnail = Request.Files["thumbnail"];
            if (thumbnail != null && thumbnail.FileName != "")
            {
                string directoryPath = Server.MapPath("~/images/logo/");
                if (!Directory.Exists(directoryPath))//不存在这个文件夹就创建这个文件夹 
                {
                    Directory.CreateDirectory(directoryPath);
                }
                string fileName = thumbnail.FileName;
                string fileExt = Path.GetExtension(fileName).ToLower();
                logoSrc = DateTime.Now.ToString("yyyMMddHHmmss") + fileExt;
                string savepath = directoryPath + logoSrc;
                thumbnail.SaveAs(savepath);
            }
            model.Thumb = logoSrc;
            model.CreateDate = DateTime.Now;
            model.CommentCount = 0;
            model.PV = 0;
            model.LikeCount = 0;
            model.IsShow = true;
            int id = new CW_ArticleLogic().Add(model);

            string tagIds = collection["TagId"];
            //保存文章所属菜单
            if (!string.IsNullOrEmpty(tagIds))
            {
                string[] ids = tagIds.Split(',');
                foreach (string mid in ids)
                {
                    try
                    {
                        if (mid != "")
                        {
                            int intMid = Convert.ToInt32(mid);
                            CW_TagRelate rel = new CW_TagRelate();
                            rel.ArticleId = id;
                            rel.TagId = intMid;
                            new CW_TagRelateLogic().Add(rel);
                        }
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
            return RedirectToAction("ArticleEdit", new { id = id });

        }


        public ActionResult ArticleEdit(int id)
        {
            CW_Article model = new CW_ArticleLogic().GetModel(id);
            if (model == null)
            {
                return RedirectToAction("ArticleList");
            }


            List<CW_Tag> tagList = new CW_TagLogic().GetModelList("");
            List<CW_TagRelate> relateList = new CW_TagRelateLogic().GetModelList("ArticleId=" + id);

            List<CW_TagView> tagViewList = new List<CW_TagView>();
            foreach (CW_Tag m in tagList)
            {
                CW_TagView v = new CW_TagView();
                v.Tag = m;
                if (relateList.Where(r => r.TagId == m.TagId).Count() > 0)
                {
                    v.IsRelate = true;
                }
                else
                    v.IsRelate = false;
                tagViewList.Add(v);
            }

            ViewBag.tagList = tagViewList;
            return View(model);
        }


        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ArticleEdit(int id, CW_Article model, FormCollection collection, string TagId)
        {
            HttpPostedFileBase thumbnail = Request.Files["thumbnail"];
            if (thumbnail != null && thumbnail.FileName != "")
            {
                string directoryPath = Server.MapPath("~/images/logo/");
                if (!Directory.Exists(directoryPath))//不存在这个文件夹就创建这个文件夹 
                {
                    Directory.CreateDirectory(directoryPath);
                }
                string fileName = thumbnail.FileName;
                string fileExt = Path.GetExtension(fileName).ToLower();
                string logoSrc = DateTime.Now.ToString("yyyMMddHHmmss") + fileExt;
                string savepath = directoryPath + logoSrc;
                thumbnail.SaveAs(savepath);
                model.Thumb = logoSrc;
            }
            new CW_ArticleLogic().Update(model);

            string tagId = collection["TagId"];
            //删除老的关系，添加新关系
            List<CW_TagRelate> relateList = new CW_TagRelateLogic().GetModelList("ArticleId=" + id);
            foreach (var item in relateList)
            {
                new CW_TagRelateLogic().Delete(item.Id);
            }
            //保存文章所属菜单
            if (!string.IsNullOrEmpty(tagId))
            {
                string[] ids = tagId.Split(',');
                foreach (string mid in ids)
                {
                    if (mid != "")
                    {
                        int intMid = Convert.ToInt32(mid);
                        CW_TagRelate rel = new CW_TagRelate();
                        rel.ArticleId = id;
                        rel.TagId = intMid;
                        new CW_TagRelateLogic().Add(rel);
                    }
                }
            }

            return RedirectToAction("ArticleList");

        }


        public ActionResult ArticleDelete(int id)
        {
            return View();
        }


        [HttpPost]
        public ActionResult ArticleDelete(int id, FormCollection collection)
        {
            try
            {
                if (id > 0)
                {
                    new CW_ArticleLogic().Delete(id);
                }

                return RedirectToAction("ArticleList");
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region 菜单管理
        public ActionResult MenuList()
        {
            List<CW_Menu> list = new CW_MenuLogic().GetModelList("1=1 order by Sort,MenuId");
            List<CW_MenuView> viewList = new List<CW_MenuView>();
            foreach (CW_Menu m in list)
            {

                CW_MenuView temp = new CW_MenuView();
                temp.menu = m;
                if (m.ParentId > 0)
                {
                    CW_Menu m2 = list.Where(x => x.MenuId == m.ParentId).FirstOrDefault();
                    if (m2 != null)
                    {
                        temp.ParentName = m2.MenuName;
                    }
                }
                viewList.Add(temp);

            }
            return View(viewList);
        }

        [HttpPost]
        public ActionResult MenuListApi()
        {
            List<CW_Menu> list = new CW_MenuLogic().GetModelList("1=1 order by Sort,MenuId");
            return Json(list);
        }

        public ActionResult MenuCreate()
        {
            //可选的父级菜单
            List<CW_Menu> list = new CW_MenuLogic().GetModelList("IsParent=1 order by Sort");
            ViewBag.ParentList = list;
            return View();
        }


        [HttpPost]
        public ActionResult MenuCreate(CW_Menu model)
        {
            int existNum = new CW_MenuLogic().GetRecordCount("MenuName='" + model.MenuName + "'");
            if (existNum > 0)
            {
                return Content("<script>alert('已存在此菜单！');history.back();</script>");
            }
            new CW_MenuLogic().Add(model);
            return RedirectToAction("MenuList");
        }


        public ActionResult MenuEdit(int id)
        {
            CW_Menu model = new CW_MenuLogic().GetModel(id);
            if (model == null)
            {
                return RedirectToAction("ArticleList");
            }
            //可选的父级菜单
            List<CW_Menu> list = new CW_MenuLogic().GetModelList("IsParent=1 order by Sort");
            ViewBag.ParentList = list;
            return View(model);
        }


        [HttpPost]
        [ValidateInput(false)]
        public ActionResult MenuEdit(int id, CW_Menu model, FormCollection collection)
        {
            //判断是否有此菜单
            int existNum = new CW_MenuLogic().GetRecordCount("MenuId!=" + model.MenuId + "  and MenuName='" + model.MenuName + "'");
            if (existNum > 0)
            {
                return Content("<script>alert('已存在此菜单！');history.back();</script>");
            }
            new CW_MenuLogic().Update(model);
            return RedirectToAction("MenuList");
        }

        [HttpPost]
        public ActionResult MenuEditApi(CW_Menu model, FormCollection collection)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();

            model.IsShow = true;
            //判断是否有此菜单
            int existNum = new CW_MenuLogic().GetRecordCount("MenuId!=" + model.MenuId + "  and MenuName='" + model.MenuName + "'");
            if (existNum > 0)
            {
                dic.Add("state", "error");
                dic.Add("msg", "已存在此菜单");
                return Json(dic);
            }
            else if (model.MenuId > 0)
            {
                new CW_MenuLogic().Update(model);
            }
            else
            {
                new CW_MenuLogic().Add(model);
            }
            dic.Add("state", "success");

            return Json(dic);
        }

        [HttpPost]
        public ActionResult MenuDelApi(CW_Menu model, FormCollection collection)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            if (model.MenuId > 0)
            {
                new CW_MenuLogic().Delete(model.MenuId);
                dic.Add("state", "success");
            }
            else
            {
                dic.Add("state", "error");
                dic.Add("msg", "不存在此菜单");
            }


            return Json(dic);
        }


        public ActionResult MenuDelete(int id)
        {
            CW_Menu model = new CW_MenuLogic().GetModel(id);
            if (model == null)
            {
                return RedirectToAction("ArticleList");
            }
            return View(model);
        }


        [HttpPost]
        public ActionResult MenuDelete(int id, FormCollection collection)
        {
            try
            {
                if (id > 0)
                {
                    new CW_MenuLogic().Delete(id);
                }

                return RedirectToAction("MenuList");
            }
            catch
            {
                return View();
            }
        }

        [HttpPost]
        public ActionResult MenuSort(string jsonStr)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            try
            {
                string[] arr = jsonStr.Trim(']').Split(']');
                foreach (string temp in arr)
                {
                    if (temp.IndexOf("|") > -1)
                    {
                        int mid = Convert.ToInt32(temp.Split('|')[0]);
                        int idx = Convert.ToInt32(temp.Split('|')[1]);
                        CW_Menu menu = new CW_MenuLogic().GetModel(mid);
                        menu.Sort = idx;
                        new CW_MenuLogic().Update(menu);
                    }
                }
                dic.Add("state", "success");
            }
            catch (Exception ex)
            {
                dic.Add("state", "error");
            }
            return Json(dic);

        }
        #endregion

        #region 菜单-文章 关系
        public ActionResult MenuArticleRelation()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetArticlesByMenuid(int mid, string keyword)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            List<object> result = new List<object>();
            //List<CW_ArticleMenuRelation> relList = new CW_ArticleMenuRelationLogic().GetModelList("MenuId=" + mid);
            //string aids = "";
            //foreach (var rel in relList)
            //{
            //    aids += rel.ArticleId + ",";
            //    CW_Article article = new CW_ArticleLogic().GetModel(rel.ArticleId);               
            //    if (article != null)
            //    {
            //        object temp = new
            //        {
            //            relid = rel.Id,
            //            aid = article.ArticleId,
            //            title=article.Title,
            //            createdate=Convert.ToDateTime(article.CreateDate).ToString("yyyy-MM-dd")
            //        };
            //        result.Add(temp);
            //    }
            //}

            string sqlStr = "ArticleId in (select ArticleID from dbo.CW_ArticleMenuRelation where MenuId=" + mid + ") ";
            if (!string.IsNullOrEmpty(keyword))
            {
                sqlStr += " and  Title like N'%" + keyword + "%' and Abstract like N'%" + keyword + "%'";
            }

            List<CW_Article> articleList = new CW_ArticleLogic().GetModelList(sqlStr);
            foreach (var article in articleList)
            {
                object temp = new
                {
                    aid = article.ArticleId,
                    title = article.Title,
                    createdate = Convert.ToDateTime(article.CreateDate).ToString("yyyy-MM-dd")
                };
                result.Add(temp);
            }

            dic.Add("state", "success");
            dic.Add("list", result);
            return Json(dic);
        }

        [HttpPost]
        public ActionResult DelRelationById(int mid,int aid)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            List<CW_ArticleMenuRelation> relList = new CW_ArticleMenuRelationLogic().GetModelList("MenuId=" + mid + " and ArticleId="+aid);
            foreach (var rel in relList)
            {
                new CW_ArticleMenuRelationLogic().Delete(rel.Id);
            }
            dic.Add("state", "success");
            return Json(dic);
        }


        //添加关系
        public ActionResult AddArticleRelation(int? mid, int? page, string keyword)
        {
            if (mid > 0)
            {
                CW_Menu menu = new CW_MenuLogic().GetModel(Convert.ToInt32(mid));
                if (menu == null)
                {
                    return RedirectToAction("MenuArticleRelation");
                }
                ViewBag.MenuName = menu.MenuName;
            }
            else
            {
                return RedirectToAction("MenuArticleRelation");
            }

            int pageSize = N_PAGE_SIZE;
            int pageIndex = page == null ? 0 : Convert.ToInt32(page);

            string sqlStr = " ArticleId not in (select ArticleId from dbo.CW_ArticleMenuRelation where MenuId=" + mid + ")";
            if (!String.IsNullOrEmpty(keyword))
            {
                ViewBag.keyword = keyword;
                sqlStr += string.Format(" and (Title like '%{0}%' or Abstract like '%{0}%' or Content like '%{0}%')", keyword);
            }
            sqlStr += " order by CreateDate desc";

            List<CW_Article> articleList = new CW_ArticleLogic().GetModelList(sqlStr);
            Pagination<CW_Article> paginateNew = new Pagination<CW_Article>(articleList, pageIndex, pageSize);
            return View(paginateNew);
        }

        [HttpPost]
        public ActionResult AddRelation(int articleid, int mid)
        {
            try
            {
                if (articleid > 0 && mid > 0)
                {
                    //判断是否存在
                    List<CW_ArticleMenuRelation> exist = new CW_ArticleMenuRelationLogic().GetModelList(" Menuid=" + mid + " and ArticleId=" + articleid);
                    if (exist.Count == 0)
                    {
                        CW_ArticleMenuRelation m = new CW_ArticleMenuRelation();
                        m.MenuId = mid;
                        m.ArticleId = articleid;
                        new CW_ArticleMenuRelationLogic().Add(m);
                    }
                }
            }
            catch
            {
            }
            return Json("success");
        }

        #endregion

        #region 标签管理
        public ActionResult TagList(int? page, string keyword)
        {

            List<CW_Tag> tags = new CW_TagLogic().GetModelList("");

            return View(tags);
        }


        [HttpPost]
        public ActionResult TagCreate(CW_Tag model)
        {
            if (model.TagId > 0)
                new CW_TagLogic().Update(model);
            else
                new CW_TagLogic().Add(model);
            return RedirectToAction("TagList");

        }

        [HttpPost]
        public ActionResult TagDelete(int id)
        {
            try
            {
                if (id > 0)
                {
                    new CW_TagLogic().Delete(id);
                }

                return RedirectToAction("TagList");
            }
            catch
            {
                return View();
            }
        }

        #endregion
    }
}
